﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using WLYT.Application.Interfaces;
using WLYT.Common;
using WLYT.Domain.Entries;
using WLYT.Domain.Model;

namespace WLYT.WMS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController(IBaseService<Sys_User> userService, IHttpContextAccessor httpContextAccessor) : ControllerBase
    {
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="search">查询</param>
        /// <param name="pageSize">大小</param>
        /// <param name="pageIndex">页数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Table<Sys_User>> GetData(string search = "", int pageSize = 20, int pageIndex = 1)
        {
            Expressionable<Sys_User> exp = Expressionable.Create<Sys_User>();
            exp.AndIF(search != "",p=>p.UserName.Contains(search) && p.UserNo.Contains(search));
            var result = await userService.GetPageListAsync(exp, pageSize, pageIndex);
            return new Table<Sys_User>(result.Item1, result.Item2);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Save(Sys_User user)
        {
            if (user.Id == 0)
            {
                await userService.InsertAsync(user);
            }
            else
            {
                await userService.UpdateAsync(user);
            }
            return true;
        }

        [HttpGet]
        public async Task<Sys_User> GetModel(int id)
        {
            return await userService.GetByIdAsync(id);
        }

        [HttpPost]
        public async Task<bool> EditPassword(UserDto request)
        {
            var userId = JwtHelper.GetUserId(httpContextAccessor.HttpContext);
            var query = await userService.GetByIdAsync(userId);
            if (query.Password != HashHelper.Md5(request.Password))
            {
                return false;
            }
            query.Password = HashHelper.Md5(request.NewPassword);
            return await userService.UpdateAsync(query);
        }

        [HttpPost]
        public async Task<bool> Reset(int id)
        {
            var query = await userService.GetByIdAsync(id);
            query.Password = HashHelper.Md5("123456");
            return await userService.UpdateAsync(query);
        }

        [HttpPost]
        public Task<bool> Remove(int id)
        {
            return userService.DeleteAsync(id);
        }
    }
}
